<template>
  <div class="blog-comment-container">
    <MessageArea
      title="评论列表"
      :subTitle="`(${record.total})`"
      :list="record.rows"
      :isListLoading="isLoading"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import MessageArea from '@/components/MessageArea/'
import fetchData from '../../../../mixins/fetchData.js'
import { getComments, postComment } from '../../../../api/index'
export default {
  mixins: [fetchData({ total: 0, rows: [] })],
  components: {
    MessageArea
  },
  data () {
    return {
      page: 1,
      limit: 10
    }
  },
  computed: {
    hasMore () {
      return this.record.rows.length < this.record.total
    }
  },
  mounted () {
    this.$bus.$on('mainScroll', this.handlerScroll)
  },
  methods: {
    async handlerScroll (dom) {
      if (!this.isLoading || !dom) {
        return
      }
      const range = 100 // 可控范围内
      const dec = Math.abs((dom.scrollTop + dom.clientHeight) - dom.scrollHeight)
      if (dec <= range) {
        await this.fetchMore()
      }
    },
    fetchData () {
      return getComments({
        blogId: this.$route.params.id,
        page: this.page,
        limit: this.limit
      })
    },
    async fetchMore () {
      if (!this.hasMore) {
        return
      }
      this.isLoading = false
      this.page++
      const resp = await this.fetchData()
      this.record.total = resp.total
      this.record.rows = this.record.rows.concat(resp.rows)
      this.isLoading = true
    },
    // 提交事件
    async handleSubmit (formData, callback) {
      console.log({
        blogId: this.$route.params.id,
        ...formData
      })
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData
      })
      this.record.rows.unshift(resp)
      this.record.total++
      console.log(this.record.rows)
      // eslint-disable-next-line standard/no-callback-literal
      callback('评论成功') // 告诉子组件，我这边处理完了，你继续
    }
  },
  destroyed () {
    this.$bus.$off('mainScroll', this.handlerScroll)
  }
}
</script>

<style scoped lang="less">
.blog-comment-container {
  margin: 30px 0;
}
</style>
